const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.department
    .findAll()
    .then((dpts) => res.send(dpts))
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.get("/:dpt_id", verify, (req, res) => {
  db.department
    .findAll({
      where: {
        id: req.params.dpt_id,
      },
    })
    .then((department) => {
      res.send(department);
    })
    .catch((err) => {
      res.status(400).send({ msg: "无此部门" });
    });
});

router.post("/add", verify, (req, res) => {
  const department = req.body;
  console.log(department);
  db.department
    .create(department)
    .then((department) => {
      res.send(department);
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});

router.delete("/delete", verify, (req, res) => {
  db.department
    .destroy({
      where: {
        id: req.body.id,
      },
    })
    .then(() => {
      res.send({ msg: "删除成功！" });
    })
    .catch((err) => {
      res.send({ msg: err.message });
    });
});

router.post("/edit", verify, (req, res) => {
  db.department
    .update(req.body, {
      where: {
        id: req.body.id,
      },
    })
    .then(() => {
      res.send("done!");
    })
    .catch((err) => {
      res.status(400).send({ msg: err.message });
    });
});
module.exports = router;
